package com.freewater.parking.domain.parking;

import com.freewater.parking.domain.common.PlateNumber;

import java.time.Duration;
import java.time.LocalDateTime;

public class FeeCalculatorImpl implements FeeCalculator {

    @Override
    public int calcParkingFee(FeeCalcSpecification specification) {
        final PlateNumber plateNumber = specification.getPlateNumber();
        final LocalDateTime checkInTime = specification.getCheckInTime();
        final LocalDateTime payTime = specification.getPayTime();
        // 如果正在离场则不支付额外费用，出场时间点设置为支付时间点。
        final LocalDateTime checkOutTime = this.isCheckingOut(specification.getCheckOutTime(), payTime) ?
                payTime : specification.getCheckOutTime();
        final Duration duration = Duration.between(checkInTime, checkOutTime);
        if (duration.isNegative()) {
            return 0;
        }
        final long oneHourSecs = (long) 60 * 60;
        final long hour = (long) Math.ceil(duration.getSeconds() / (oneHourSecs * 1D));
        return (int) hour;
    }

    /**
     * 是否正在离场：支付后15分钟内
     *
     * @param checkoutTime 时间点
     * @param payTime      支付时间
     * @return 是否正在离场
     */
    public boolean isCheckingOut(LocalDateTime checkoutTime, LocalDateTime payTime) {
        if (payTime == null) {
            return false;
        }
        final Duration duration = Duration.between(payTime, checkoutTime);
        final long seconds = duration.toSeconds();
        return seconds >= 0 && seconds <= 15 * 60;
    }
}
